package com.own.business.system.dictionary.adapter.util;

import com.own.business.system.dictionary.adapter.base.BaseDictionaryModel;
import com.own.business.system.dictionary.adapter.function.SetFunction;
import com.own.business.system.dictionary.adapter.method.SystemDictionaryInfoMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * DictionaryUtil
 *
 * @author chenxueli
 * @date 2023-06-21 10:32:04
 */
@Slf4j
@Component
public class DictionaryUtil {

    @Resource
    private SystemDictionaryInfoMethod systemDictionaryInfoMethod;

    /**
     * 根据id获取字典的名称信息
     *
     * @param id 字典id
     * @return 名称信息
     */
    public String getNameById(Long id) {
        var dictionary = systemDictionaryInfoMethod.getItemById(id);
        return dictionary != null ? dictionary.getItemName() : "";
    }

    /**
     * 根据name和rootCode获取id
     *
     * @param name     名称
     * @param rootCode 根code
     * @return id
     */
    public Long getIdByNameAndRootCode(String name, String rootCode) {
        return systemDictionaryInfoMethod.getIdByNameAndRootCode(name, rootCode);
    }

    /**
     * 根据code获取字典的信息
     *
     * @param code 编码
     * @return 字典信息
     */
    public BaseDictionaryModel getByCode(String code) {
        return systemDictionaryInfoMethod.getItemByCode(code);
    }

    /**
     * 根据id获取字典的名称信息
     *
     * @param id 字典id
     * @return 名称信息
     */
    public BaseDictionaryModel getById(Long id) {
        return systemDictionaryInfoMethod.getParentById(id);
    }

    /**
     * 设置名称信息
     *
     * @param id           字典id
     * @param set          设置方法
     * @param errorMessage 错误信息
     */
    public <T> void setName(Long id, T item, SetFunction<T, String> set, String errorMessage) {
        if (!StringUtils.hasText(errorMessage)) {
            var name = getNameById(id);
            set.accept(item, name);
            return;
        }
        var dictionary = systemDictionaryInfoMethod.getItemById(id);
        if (dictionary == null) {
            throw new RuntimeException(errorMessage);
        }
        set.accept(item, dictionary.getItemName());
    }

    /**
     * 查询数据字典项信息
     *
     * @param rootCode 根编码
     * @return 列表信息
     */
    public List<? extends BaseDictionaryModel> listByRootCode(String rootCode) {
        return systemDictionaryInfoMethod.listByRootCode(rootCode);
    }

}
